<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="设备" prop="deviceId">
          <el-select
            v-model="queryParams.deviceId"
            placeholder="请选择设备"
            clearable
            filterable
            :loading="deviceLoading"
            style="width: 220px"
          >
            <el-option
              v-for="item in deviceOptions"
              :key="item.deviceId"
              :label="item.deviceName"
              :value="item.deviceId"
            >
              <div class="flex items-center">
                <span>{{ item.deviceName }}</span>
                <span class="text-gray-400 ml-2">({{ item.deviceId }})</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上报数据类型" prop="reportDataType">
          <el-select
            v-model="queryParams.reportDataType"
            placeholder="请选择上报数据类型"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in reportDataTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上报数据级别" prop="reportDataLevel">
          <el-select
            v-model="queryParams.reportDataLevel"
            placeholder="请选择上报数据级别"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in reportDataLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择处理状态"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in reportStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上报数据时间" prop="reportDataTime">
          <el-date-picker
            v-model="queryParams.reportDataTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            style="width: 340px"
          />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            style="width: 340px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" plain @click="openForm('create')">
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
          <!-- <el-button type="success" plain @click="openBatchImport">
            <Icon icon="ep:upload" class="mr-5px" /> 批量导入
          </el-button> -->
          <el-button type="warning" plain @click="handleExport">
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
          <!-- <el-button type="primary" plain @click="openGenerateRandomData">
            <Icon icon="ep:magic-stick" class="mr-5px" /> 随机生成数据
          </el-button> -->
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="list" border>
        <el-table-column label="设备名称" min-width="150">
          <template #default="{ row }">
            {{ getDeviceName(row.deviceId) }}
          </template>
        </el-table-column>
        <el-table-column label="设备ID" prop="deviceId" min-width="120" />
        <el-table-column label="上报数据类型" prop="reportDataType" min-width="120">
          <template #default="{ row }">
            {{ getReportDataTypeLabel(row.reportDataType) }}
          </template>
        </el-table-column>
        <el-table-column label="上报数据实际值" prop="reportDataValue" min-width="120" />
        <el-table-column label="上报数据级别" prop="reportDataLevel" min-width="120">
          <template #default="{ row }">
            <el-tag :type="getReportDataLevelType(row.reportDataLevel)">
              {{ getReportDataLevelLabel(row.reportDataLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="上报数据时间"
          prop="reportDataTime"
          min-width="150"
          :formatter="formatReportDataTime"
        />
        <el-table-column label="处理状态" prop="status" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getReportStatusType(row.status)">
              {{ getReportStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="上报数据信息"
          prop="message"
          min-width="180"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          :formatter="dateFormatter"
          min-width="150"
        />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openForm('update', row.id)"> 编辑 </el-button>
            <el-button link type="danger" @click="handleDelete(row.id)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-if="total > 0"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 表单弹窗 -->
    <ReportDataForm ref="formRef" @success="getList" />

    <!-- 批量导入弹窗 -->
    <BatchImportForm ref="batchImportRef" @success="getList" />

    <!-- 随机生成数据弹窗 -->
    <el-dialog v-model="randomDataDialogVisible" title="随机生成能耗上报数据" width="650px">
      <el-form :model="randomDataForm" label-width="120px">
        <el-form-item label="设备数量">
          <el-input-number
            v-model="randomDataForm.deviceCount"
            :min="1"
            :max="10"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="数据条数">
          <el-input-number
            v-model="randomDataForm.dataCount"
            :min="1"
            :max="20"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="数据类型">
          <el-select
            v-model="randomDataForm.dataTypes"
            multiple
            placeholder="选择数据类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in reportDataTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="randomDataForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <!-- 随机生成的JSON预览 -->
      <div v-if="randomJsonData">
        <div class="flex justify-between items-center mb-2">
          <div class="text-gray-700 font-bold">生成的JSON数据：</div>
          <el-button type="primary" size="small" @click="copyJsonToClipboard">
            <Icon icon="ep:copy-document" class="mr-5px" /> 复制
          </el-button>
        </div>
        <el-input
          type="textarea"
          v-model="randomJsonData"
          :rows="10"
          :readonly="true"
          class="json-preview"
        />
      </div>

      <template #footer>
        <el-button @click="randomDataDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="generateRandomData">生成数据</el-button>
        <el-button type="success" :disabled="!randomJsonData" @click="submitRandomData">
          提交数据
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import * as ReportApi from '@/api/energy/report'
import * as DeviceApi from '@/api/energy/device'
import {
  ReportDataVO,
  reportDataTypeOptions,
  reportDataLevelOptions,
  reportStatusOptions,
  exportReportData,
  batchImportReportData
} from '@/api/energy/report'
import { DeviceVO } from '@/api/energy/device'
import { dateFormatter } from '@/utils/formatTime'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import Pagination from '@/components/Pagination/index.vue'
import ReportDataForm from './components/ReportDataForm.vue'
import BatchImportForm from './components/BatchImportForm.vue'
import dayjs from 'dayjs'

// 列表数据
const list = ref<ReportDataVO[]>([])
const loading = ref(false)
const total = ref(0)

// 设备选择相关
const deviceOptions = ref<DeviceVO[]>([])
const deviceLoading = ref(false)
const loadDevices = async () => {
  deviceLoading.value = true
  try {
    const res = await DeviceApi.getDeviceList()
    deviceOptions.value = res || []
  } catch (error) {
    console.error('获取设备列表失败', error)
  } finally {
    deviceLoading.value = false
  }
}

// 查询条件
const queryFormRef = ref()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceId: '',
  reportDataType: '',
  reportDataLevel: '',
  status: '',
  reportDataTime: [],
  createTime: []
})

// 表单
const formRef = ref()
const batchImportRef = ref()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await ReportApi.getReportDataPage(queryParams)
    if (res && res.list) {
      list.value = res.list
      total.value = res.total
    }
  } finally {
    loading.value = false
  }
}

// 获取设备名称
const getDeviceName = (deviceId: string) => {
  const device = deviceOptions.value.find((item) => item.deviceId === deviceId)
  return device ? device.deviceName : deviceId
}

// 工具方法
const getReportDataTypeLabel = (value: string) => {
  return reportDataTypeOptions.find((item) => item.value === value)?.label || value
}

const getReportDataLevelLabel = (value: string) => {
  return reportDataLevelOptions.find((item) => item.value === value)?.label || value
}

const getReportDataLevelType = (value: string) => {
  return reportDataLevelOptions.find((item) => item.value === value)?.type || ''
}

const getReportStatusLabel = (value: string) => {
  return reportStatusOptions.find((item) => item.value === value)?.label || value
}

const getReportStatusType = (value: string) => {
  return reportStatusOptions.find((item) => item.value === value)?.type || ''
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 打开表单
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

// 打开批量导入
const openBatchImport = () => {
  batchImportRef.value?.open()
}

// 删除
const handleDelete = (id: number) => {
  ElMessageBox.confirm('确认要删除该能耗报告数据吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await ReportApi.deleteReportData(id)
    ElMessage.success('删除成功')
    handleQuery()
  })
}

// 处理上报数据时间的格式化（特殊处理）
const formatReportDataTime = (_row: any, _column: any, cellValue: any): string => {
  try {
    // 处理空值或无效值
    if (cellValue === null || cellValue === undefined || cellValue === 0 || cellValue === '0') {
      return ''
    }

    // 检查是否是1970年的日期（无效日期）
    if (typeof cellValue === 'string' && cellValue.includes('1970')) {
      return ''
    }

    // 处理时间戳格式（数字）
    if (typeof cellValue === 'number') {
      // 时间戳为0或负数，视为无效
      if (cellValue <= 0) {
        return ''
      }

      // 确保是毫秒级时间戳
      const timestamp = cellValue.toString().length <= 10 ? cellValue * 1000 : cellValue
      return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
    }

    // 处理字符串时间格式
    if (typeof cellValue === 'string') {
      // 尝试解析字符串格式的时间戳
      if (/^\d+$/.test(cellValue)) {
        const timestamp = cellValue.length <= 10 ? parseInt(cellValue) * 1000 : parseInt(cellValue)
        return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
      }

      // 标准日期字符串
      return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
    }

    // 兜底使用通用格式化
    return dateFormatter(_row, _column, cellValue)
  } catch (error) {
    console.error('日期格式化错误', error, cellValue)
    return String(cellValue) || ''
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 显示导出进度
    ElMessage.success('正在导出能耗报告数据，请稍候...')
    // 执行导出
    const res = await exportReportData(queryParams)
    console.log('导出响应:', res) // 添加调试信息
  } catch (error: any) {
    console.error('导出错误:', error) // 添加错误详情日志
    ElMessage.error('导出失败: ' + error.message)
  }
}

// 随机生成数据相关
const randomDataDialogVisible = ref(false)
const randomDataForm = reactive({
  deviceCount: 1,
  dataCount: 5,
  dataTypes: ['voltage', 'currents', 'activePower', 'temperature'],
  timeRange: [
    dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().format('YYYY-MM-DD HH:mm:ss')
  ] as string[]
})
const randomJsonData = ref('')

// 打开随机生成数据弹窗
const openGenerateRandomData = () => {
  randomDataDialogVisible.value = true
  // 默认选择所有数据类型
  randomDataForm.dataTypes = reportDataTypeOptions.map((item) => item.value)
  // 设置默认时间范围为过去24小时
  randomDataForm.timeRange = [
    dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().format('YYYY-MM-DD HH:mm:ss')
  ]
  randomJsonData.value = '' // 清空之前生成的数据
}

// 生成随机数据
const generateRandomData = () => {
  if (!deviceOptions.value || deviceOptions.value.length === 0) {
    ElMessage.warning('没有可用的设备，请先添加设备')
    return
  }

  // 生成指定数量的随机数据
  const randomData: Omit<ReportDataVO, 'id' | 'createTime'>[] = []
  const selectedDevices = getRandomDevices(randomDataForm.deviceCount)

  for (let i = 0; i < randomDataForm.dataCount; i++) {
    // 为每条数据随机选择一个设备
    const device = selectedDevices[Math.floor(Math.random() * selectedDevices.length)]
    // 随机选择一个数据类型
    const dataType =
      randomDataForm.dataTypes[Math.floor(Math.random() * randomDataForm.dataTypes.length)]
    // 随机生成数据级别
    const dataLevel =
      reportDataLevelOptions[Math.floor(Math.random() * reportDataLevelOptions.length)].value
    // 随机生成时间
    const reportTime = generateRandomTime(randomDataForm.timeRange[0], randomDataForm.timeRange[1])

    // 根据数据类型生成随机值
    const dataValue = generateRandomValue(dataType)

    // 生成随机能耗
    const energyConsumption = Math.floor(Math.random() * 150) + 50

    // 根据数据类型和级别生成消息
    const message = generateMessage(dataType, dataLevel, dataValue)

    // 随机选择状态
    const status = reportStatusOptions[Math.floor(Math.random() * reportStatusOptions.length)].value

    // 创建数据对象
    randomData.push({
      deviceId: device.deviceId,
      reportDataType: dataType,
      reportDataValue: dataValue,
      reportDataLevel: dataLevel,
      reportDataTime: reportTime,
      energyConsumption: energyConsumption,
      message: message,
      status: status
    })
  }

  // 将随机数据转换为JSON字符串并显示
  randomJsonData.value = JSON.stringify(randomData, null, 2)
}

// 从可用设备中随机选择指定数量的设备
const getRandomDevices = (count: number) => {
  if (deviceOptions.value.length <= count) {
    return [...deviceOptions.value]
  }

  const shuffled = [...deviceOptions.value].sort(() => 0.5 - Math.random())
  return shuffled.slice(0, count)
}

// 在指定时间范围内生成随机时间
const generateRandomTime = (start: string, end: string) => {
  const startTime = new Date(start).getTime()
  const endTime = new Date(end).getTime()
  const randomTime = startTime + Math.random() * (endTime - startTime)
  return dayjs(randomTime).format('YYYY-MM-DD HH:mm:ss')
}

// 根据数据类型生成随机值
const generateRandomValue = (dataType: string) => {
  switch (dataType) {
    case 'voltage':
      // 电压：正常约220V，波动范围200-240
      return +(200 + Math.random() * 40).toFixed(1)
    case 'currents':
      // 电流：范围0.5-15A
      return +(0.5 + Math.random() * 14.5).toFixed(2)
    case 'activePower':
      // 功率：范围100-5000W
      return +(100 + Math.random() * 4900).toFixed(0)
    case 'temperature':
      // 温度：范围20-80℃
      return +(20 + Math.random() * 60).toFixed(1)
    default:
      return +(Math.random() * 100).toFixed(1)
  }
}

// 根据数据类型和级别生成消息
const generateMessage = (dataType: string, level: string, value: number) => {
  const typeLabel = getReportDataTypeLabel(dataType)
  const levelLabel = getReportDataLevelLabel(level)

  switch (level) {
    case 'info':
      return `${typeLabel}正常，当前值${value}，运行正常`
    case 'warning':
      return `${typeLabel}警告，当前值${value}，请注意监控`
    case 'danger':
      return `${typeLabel}异常，当前值${value}，建议立即检查设备`
    default:
      return `${typeLabel}数据上报，当前值${value}`
  }
}

// 复制JSON到剪贴板
const copyJsonToClipboard = () => {
  navigator.clipboard
    .writeText(randomJsonData.value)
    .then(() => {
      ElMessage.success('已复制到剪贴板')
    })
    .catch(() => {
      ElMessage.error('复制失败，请手动复制')
    })
}

// 提交随机生成的数据到后端
const submitRandomData = async () => {
  if (!randomJsonData.value) {
    ElMessage.warning('请先生成随机数据')
    return
  }

  try {
    // 解析JSON数据
    const dataList = JSON.parse(randomJsonData.value) as Omit<ReportDataVO, 'id' | 'createTime'>[]
    if (!dataList || !Array.isArray(dataList) || dataList.length === 0) {
      ElMessage.error('数据格式错误，请重新生成')
      return
    }

    // 确认提交
    await ElMessageBox.confirm(
      `确定要逐条提交这 ${dataList.length} 条随机生成的数据吗？每条数据将通过单独的接口调用创建，并触发WebSocket通知。`,
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    // 显示提交进度通知
    let progressNotification = ElNotification({
      title: '数据提交进度',
      message: `正在提交数据：0/${dataList.length}`,
      type: 'info',
      duration: 0
    })

    // 记录成功和失败的数量
    let successCount = 0
    let failCount = 0

    // 依次调用创建接口
    for (let i = 0; i < dataList.length; i++) {
      const item = dataList[i]
      try {
        // 更新进度提示（关闭旧通知并创建新通知）
        progressNotification.close()
        progressNotification = ElNotification({
          title: '数据提交进度',
          message: `正在提交数据：${i + 1}/${dataList.length}`,
          type: 'info',
          duration: 0
        })

        // 调用创建接口
        await ReportApi.createReportData(item)
        successCount++
      } catch (error) {
        console.error(`提交第${i + 1}条数据失败:`, error)
        failCount++
      }

      // 添加一点延时，避免请求过快
      await new Promise((resolve) => setTimeout(resolve, 100))
    }

    // 关闭进度通知
    progressNotification.close()

    // 显示结果通知
    ElNotification({
      title: '数据提交完成',
      message: `成功: ${successCount} 条, 失败: ${failCount} 条`,
      type: successCount > 0 ? 'success' : 'warning',
      duration: 5000
    })

    // 关闭弹窗并刷新列表
    if (successCount > 0) {
      randomDataDialogVisible.value = false
      getList()
    }
  } catch (error: any) {
    if (error === 'cancel') return
    console.error('提交随机数据失败', error)
    ElMessage.error(`提交失败: ${error.message || '未知错误'}`)
  }
}

// 页面加载时查询数据
onMounted(() => {
  loadDevices().then(() => {
    getList()
  })
})
</script>

<style scoped>
.json-preview {
  font-family: monospace;
  background-color: #f5f7fa;
}
</style>
